package com.hmdp.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
    @Resource
    private IShopTypeService typeService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("list")
    public Result queryTypeList() {
//        List<ShopType> typeList = typeService
//                .query().orderByAsc("sort").list();
        //先从redis中查询店铺类型信息
        String typeJson = stringRedisTemplate.opsForValue().get("shopTypeList");
        if (StrUtil.isNotBlank(typeJson)) {
            //存在则直接返回
            return Result.ok(JSONUtil.toList(typeJson, ShopType.class));
        }
        //不存在则查询数据库，将结果缓存到redis中，并返回
        List<ShopType> typeList = typeService.query().orderByAsc("sort").list();
        stringRedisTemplate.opsForValue().set("shopTypeList", JSONUtil.toJsonStr(typeList));
        return Result.ok(typeList);
    }
}
